import {GLOBAL_CONFIG} from "@/global-config";
import userStore from "@/store/userStore";
import axios, {type AxiosRequestConfig, type AxiosError, type AxiosResponse} from "axios";
import {toast} from "sonner";
import type {Result} from "#/api";
import {ResultStatus} from "#/enum";


const axiosInstance = axios.create({
    baseURL: GLOBAL_CONFIG.apiBaseUrl,
    timeout: 50000,
    headers: {'Content-Type': 'multipart/form-data'},
});

axiosInstance.interceptors.request.use(
    (config) => {
        config.headers.token = "Bearer Token";
        return config;
    },
    (error) => Promise.reject(error),
);

axiosInstance.interceptors.response.use(
    (res: AxiosResponse<Result<any>>) => {
        if (!res.data) throw new Error("请求出错，请稍候重试");
        const {result, data, info} = res.data;
        if (result === ResultStatus.SUCCESS) {
            return data;
        }
        if (result === ResultStatus.TOKEN_EXPIRED) {
            userStore.getState().actions.clearUserInfoAndToken();
        }
        throw new Error(info || "请求出错，请稍候重试");
    },
    (error: AxiosError<Result>) => {
        const {response, message} = error || {};
        const errMsg = response?.data?.info || message || "操作失败,系统异常!";
        toast.error(errMsg, {position: "top-center"});
        if (response?.status === 401) {
            userStore.getState().actions.clearUserInfoAndToken();
        }
        return Promise.reject(error);
    },
);

class APIClient {
    get<T = unknown>(config: AxiosRequestConfig): Promise<T> {
        return this.request<T>({...config, method: "GET"});
    }

    post<T = unknown>(config: AxiosRequestConfig): Promise<T> {
        return this.request<T>({...config, method: "POST"});
    }

    put<T = unknown>(config: AxiosRequestConfig): Promise<T> {
        return this.request<T>({...config, method: "PUT"});
    }

    delete<T = unknown>(config: AxiosRequestConfig): Promise<T> {
        return this.request<T>({...config, method: "DELETE"});
    }

    request<T = unknown>(config: AxiosRequestConfig): Promise<T> {
        return axiosInstance.request<any, T>(config);
    }
}

export default new APIClient();